package com.savitar.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.savitar.common.enums.HttpStatus;
import com.savitar.common.vo.ResultBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class RestfullAssessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(ResultBean.err(HttpStatus.NO_JURISDICTION.getCode(), HttpStatus.NO_JURISDICTION.getDesc())));
        writer.flush();
        writer.close();
    }
}
